const baseUrl = "http://localhost/wechat/api/user/";

const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}

const get = (url, callback)=>{
  wx.request({
    url: url.indexOf("http")===0?url:baseUrl + url,
    method: "GET",
    header: {
      token: wx.getStorageSync("token")
    },
    success: function (response) {
      callback(response.data);
    },
    fail: function (response) {
      wx.showToast({
        title: "服务器连接失败！",
        icon: 'error',
        duration:5000
      });
    }
  });
};

const post = (url, data, callback)=>{
  wx.request({
    url: baseUrl + url,
    method: "POST",
    header: {
      'content-type': 'application/json',
      token: wx.getStorageSync("token")
    },
    data: data,
    success: function (response) {
      callback(response.data);
    },
    fail: function (response) {
      wx.showToast({
        title: "服务器连接失败!",
        icon: 'error',
        duration:5000
      });
    },
    complete(res) {
      if(res.data.status<200 || res.data.status>=300){
        wx.showToast({
          title: "服务器连接失败！："+res.data.error,
          icon: 'none',
        });
      }
    }
  });
};
const config = (callback)=>{
  post("config",{}, function (response) {
    wx.setStorageSync("appConfig", response.data);
    if(callback){
      callback(response.data);
    }
  });
};

const login = (parentId)=>{
  wx.login({
    success(res) {
      if(res.errMsg==="login:ok"){
        post("login",{
          code:res.code,
          parentId: parentId||'',
        },response=>{
          wx.setStorageSync("token",response.data.token);
          wx.setStorageSync("userInfo",response.data.userInfo);
          console.log("response",response.data);
        })
      }
    }
  });
};


const createInterstitialAd = () =>{
  const appConfig = wx.getStorageSync("appConfig");
  const ads = appConfig.main || {};
  const index = ads || {};
  if(wx.createInterstitialAd&&index.chapin){
    const interstitialAd = wx.createInterstitialAd({ adUnitId:index.chapin })
    interstitialAd.onLoad(() => {
      console.log('onLoad event emit')
    })
    interstitialAd.onError((err) => {
      console.log('onError event emit', err)
    })
    interstitialAd.onClose((res) => {
      console.log('onClose event emit', res)
    });
    return interstitialAd;
  }
  return null;
}

const interstitialAdShow = (interstitialAd) =>{
  if(interstitialAd){
    interstitialAd.show().catch((err) => {
      console.error(err)
    })
  }
}

const createRewardedVideoAd = ()=>{
  const appConfig = wx.getStorageSync("appConfig");
  const ads = appConfig.main || {};
  const index = ads || {};
  if(wx.createRewardedVideoAd&&index.jili){
    const rewardedVideoAd = wx.createRewardedVideoAd({ adUnitId:index.jili })
    rewardedVideoAd.onLoad(() => {
      console.log('onLoad event emit')
    })
    rewardedVideoAd.onError((err) => {
      console.log('onError event emit', err)
    })
    rewardedVideoAd.onClose((res) => {
      console.log('onClose event emit', res)
    })

    return rewardedVideoAd;
  }
  return null;
}

const rewardedVideoAdShow = (rewardedVideoAd)=>{
  if(rewardedVideoAd){
    rewardedVideoAd.show()
        .catch(() => {
          rewardedVideoAd.load()
              .then(() => rewardedVideoAd.show())
              .catch(err => {
                console.log('激励视频 广告显示失败')
              })
        })
  }
}

module.exports = {
  formatTime,
  get,
  post,
  config,
  login,
  createInterstitialAd,
  interstitialAdShow,
  createRewardedVideoAd,
  rewardedVideoAdShow,
}
